# -*- coding: utf-8 -*-
"""
UI Nota
Nota related forms
"""

#---------------------------------------------------------------------------
# Copyright (c) 2014 Ahmad Ghulam Zakiy <ghulam.zakiy@gmail.com>
# License: GPL3
#
# This file is part of SimpleStore
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#---------------------------------------------------------------------------

import sys, os, mine
sys.path = sys.path.__add__([os.path.abspath('.'),])
mine.listIt(sys.path)
from PySide import QtCore, QtGui, QtSql
import config
import connection
import qrc
from lib import model, format
from decimal import *

getcontext().prec=2

class Ui_Dialog(object):
    def setupUi(self, Dialog):

        Dialog.setObjectName("Dialog")
        Dialog.resize(600, 640)
        
        self.gridLayoutWidget = QtGui.QWidget(Dialog)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(20, 30, 560, 580))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        
        self.outerGridLayout = QtGui.QGridLayout(self.gridLayoutWidget)
        self.outerGridLayout.setSpacing(-1)
        self.outerGridLayout.setContentsMargins(0, 0, 0, 0)
        self.outerGridLayout.setObjectName("outerGridLayout")

        self.setupLocale()
        self.setupNota()
        
        self.idLabel = QtGui.QLabel(self.gridLayoutWidget)
        self.idLabel.setObjectName("idLabel")
        self.outerGridLayout.addWidget(self.idLabel, 0, 0, 1, 1)
        
        self.idEdit = QtGui.QLineEdit(self.gridLayoutWidget)
        self.idEdit.setReadOnly(True)
        self.idEdit.setObjectName("idEdit")
        self.outerGridLayout.addWidget(self.idEdit, 0, 1, 1, 1)
        self.idLabel.setBuddy(self.idEdit)

        self.supplierLabel = QtGui.QLabel(self.gridLayoutWidget)
        self.supplierLabel.setObjectName("supplierLabel")
        self.outerGridLayout.addWidget(self.supplierLabel, 1, 0, 1, 1)

        self.supplierComboBox = QtGui.QComboBox(self.gridLayoutWidget)
        self.supplierComboBox.setObjectName("supplierComboBox")
        self.supplierLabel.setBuddy(self.supplierComboBox)
        while self.supplierQuery.next():
            self.supplierComboBox.addItem(self.supplierQuery.value(1), self.supplierQuery.value(0))
        self.supplierComboBox.setCompleter(self.supplierCompleter)
        self.outerGridLayout.addWidget(self.supplierComboBox, 1, 1, 1, 4)
        
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.outerGridLayout.addItem(spacerItem, 0, 2, 1, 1)
        
        self.tanggalLabel = QtGui.QLabel(self.gridLayoutWidget)
        self.tanggalLabel.setObjectName("tanggalLabel")
        self.outerGridLayout.addWidget(self.tanggalLabel, 0, 3, 1, 1)

        self.tanggalEdit = QtGui.QDateEdit(self.gridLayoutWidget)
        self.tanggalEdit.setDate(QtCore.QDate().currentDate())
        self.tanggalEdit.setMaximumDate(QtCore.QDate(2050, 12, 31))
        self.tanggalEdit.setMinimumDate(QtCore.QDate(2000, 1, 1))
        self.tanggalEdit.setCalendarPopup(True)
        self.tanggalEdit.setCurrentSectionIndex(1)
        self.tanggalEdit.setObjectName("tanggalEdit")
        self.outerGridLayout.addWidget(self.tanggalEdit, 0, 4, 1, 1)
        self.tanggalLabel.setBuddy(self.tanggalEdit)
        
        self.pembayaranLabel = QtGui.QLabel(self.gridLayoutWidget)
        self.pembayaranLabel.setObjectName("pembayaranLabel")
        self.outerGridLayout.addWidget(self.pembayaranLabel, 2, 3, 1, 1)
        
        self.pembayaranComboBox = QtGui.QComboBox(self.gridLayoutWidget)
        self.pembayaranComboBox.setObjectName("pembayaranComboBox")
        self.pembayaranComboBox.setModel(self.model_pembayaran)
        self.outerGridLayout.addWidget(self.pembayaranComboBox, 2, 4, 1, 1)
        self.pembayaranLabel.setBuddy(self.pembayaranComboBox)
        
        self.tableView = QtGui.QTableView(self.gridLayoutWidget)
        self.tableView.setSortingEnabled(True)
        self.tableView.setObjectName("tableView")
        self.tableView.setEditTriggers(self.tableView.NoEditTriggers)
        self.tableView.setAlternatingRowColors(True)
        self.tableView.resizeColumnsToContents()
        self.tableView.resizeRowsToContents()
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().resizeSection(1, 100)
        #self.tableView.verticalHeader().setVisible(False)
        self.outerGridLayout.addWidget(self.tableView, 3, 0, 1, 5)
        self.myDelegate = format.myCustomDelegate(self.gridLayoutWidget)
        self.tableView.setItemDelegate(self.myDelegate)

        self.buatNotaButton = QtGui.QPushButton(self.gridLayoutWidget)
        self.buatNotaButton.setObjectName("buatNotaButton")
        self.buatNotaButton.setAutoDefault(False)
        self.buatNotaButton.setCheckable(True)
        self.outerGridLayout.addWidget(self.buatNotaButton, 4, 0, 1, 1)

        self.hargaBeliTotalLabel = QtGui.QLabel(self.gridLayoutWidget)
        self.hargaBeliTotalLabel.setObjectName("totalLabel")
        self.outerGridLayout.addWidget(self.hargaBeliTotalLabel, 4, 3, 1, 1)

        self.hargaBeliTotalEdit = QtGui.QLineEdit(self.gridLayoutWidget)
        self.hargaBeliTotalEdit.setObjectName("totalEdit")
        self.outerGridLayout.addWidget(self.hargaBeliTotalEdit, 4, 4, 1, 1)
        self.hargaBeliTotalLabel.setBuddy(self.hargaBeliTotalEdit)

        # toolbox
        self.toolBox = QtGui.QToolBox(self.gridLayoutWidget)
        self.toolBox.setEnabled(True)
        self.toolBox.setMaximumSize(QtCore.QSize(16777215, 140))
        self.toolBox.setFrameShape(QtGui.QFrame.NoFrame)
        self.toolBox.setObjectName("toolBox")
        
        self.page = QtGui.QWidget()
        self.page.setGeometry(QtCore.QRect(0, 0, 549, 104))
        self.page.setObjectName("page")
        
        self.widget = QtGui.QWidget(self.page)
        self.widget.setGeometry(QtCore.QRect(0, 10, 551, 72))
        self.widget.setObjectName("widget")
        
        # gridLayout di dalam toolbox
        self.toolboxGridLayout = QtGui.QGridLayout(self.widget)
        self.toolboxGridLayout.setContentsMargins(0, 0, 0, 0)
        self.toolboxGridLayout.setObjectName("toolboxGridLayout")
        
        self.qtyLabel = QtGui.QLabel(self.widget)
        self.qtyLabel.setObjectName("qtyLabel")
        self.toolboxGridLayout.addWidget(self.qtyLabel, 0, 0, 1, 1)
        
        self.qtyEdit = QtGui.QLineEdit(self.widget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.qtyEdit.sizePolicy().hasHeightForWidth())
        self.qtyEdit.setSizePolicy(sizePolicy)
        self.qtyEdit.setMinimumSize(QtCore.QSize(30, 0))
        self.qtyEdit.setMaximumSize(QtCore.QSize(30, 16777215))
        self.qtyEdit.setMaxLength(4)
        self.qtyEdit.setObjectName("qtyEdit")
        self.toolboxGridLayout.addWidget(self.qtyEdit, 1, 0, 1, 1)
        self.qtyLabel.setBuddy(self.qtyEdit)

        self.unitLabel = QtGui.QLabel(self.widget)
        self.unitLabel.setObjectName("qtyLabel")
        self.toolboxGridLayout.addWidget(self.unitLabel, 0, 1, 1, 1)

        self.unitComboBox = QtGui.QComboBox(self.widget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.unitComboBox.sizePolicy().hasHeightForWidth())
        self.unitComboBox.setSizePolicy(sizePolicy)
        self.unitComboBox.setMaximumSize(QtCore.QSize(80, 16777215))
        self.unitComboBox.setObjectName("unitComboBox")
        self.unitComboBox.setModel(self.model_unit)        
        self.toolboxGridLayout.addWidget(self.unitComboBox, 1, 1, 1, 1)
        self.unitLabel.setBuddy(self.unitComboBox)

        self.toolBox.addItem(self.page, "")
        
        self.produkLabel = QtGui.QLabel(self.widget)
        self.produkLabel.setObjectName("produkLabel")
        self.toolboxGridLayout.addWidget(self.produkLabel, 0, 2, 1, 1)
        
        self.produkComboBox = QtGui.QComboBox(self.widget)
        self.produkComboBox.setMinimumSize(QtCore.QSize(200, 0))
        self.produkComboBox.setObjectName("produkComboBox")
        while self.produkQuery.next():
            self.produkComboBox.addItem(self.produkQuery.value(1), self.produkQuery.value(0))
        self.produkComboBox.setCompleter(self.produkCompleter)
        self.produkComboBox.setEditable(True)
        self.produkCompleter.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.produkCompleter.setCompletionMode(QtGui.QCompleter.InlineCompletion)
        self.produkCompleter.setModelSorting(QtGui.QCompleter.CaseInsensitivelySortedModel)
        self.produkCompleter.setWrapAround(False)
        self.toolboxGridLayout.addWidget(self.produkComboBox, 1, 2, 1, 1)
        self.produkLabel.setBuddy(self.produkComboBox)
        
        self.hargaBeliGrosirLabel = QtGui.QLabel("&Harga Grosir", self.widget)
        self.hargaBeliGrosirLabel.setObjectName("hargaGrosirLabel")
        self.toolboxGridLayout.addWidget(self.hargaBeliGrosirLabel, 0, 3, 1, 1)
        
        self.hargaBeliGrosirEdit = QtGui.QLineEdit(self.widget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.hargaBeliGrosirEdit.sizePolicy().hasHeightForWidth())
        self.hargaBeliGrosirEdit.setSizePolicy(sizePolicy)
        self.hargaBeliGrosirEdit.setAlignment(QtCore.Qt.AlignRight)
        self.hargaBeliGrosirEdit.setMinimumSize(QtCore.QSize(120, 0))
        self.hargaBeliGrosirEdit.setMaximumSize(QtCore.QSize(120, 16777215))
        self.hargaBeliGrosirEdit.setObjectName("hargaBeliGrosirEdit")
        reg = '(\d){3,3}(?:sep)?(\d{1,3})?(?:sep)?(\d{3,3})?$'.replace('dec',format.decimalPoint).replace('sep', '\\'+format.groupSeparator)
        self.hargaBeliGrosirValidator = QtGui.QRegExpValidator(QtCore.QRegExp(reg), self.widget)
        self.hargaBeliGrosirValidator.setLocale(config.application['locale'])
        self.hargaBeliGrosirEdit.setValidator(self.hargaBeliGrosirValidator)
        self.toolboxGridLayout.addWidget(self.hargaBeliGrosirEdit, 1, 3, 1, 1)
        self.hargaBeliGrosirLabel.setBuddy(self.hargaBeliGrosirEdit)

        self.toolboxButtonBox = QtGui.QDialogButtonBox(self.widget)
        self.toolboxButtonBox.setStandardButtons(QtGui.QDialogButtonBox.Reset|QtGui.QDialogButtonBox.Save)
        self.toolboxButtonBox.setCenterButtons(False)
        self.toolboxButtonBox.setObjectName("toolboxButtonBox")
        self.toolboxGridLayout.addWidget(self.toolboxButtonBox, 2, 0, 1, 4)

        self.outerGridLayout.addWidget(self.toolBox, 5, 0, 1, 5)

        #self.tampilTambahButton = QtGui.QPushButton(self.gridLayoutWidget)
        #self.tampilTambahButton.setObjectName("tampilTambahButton")
        #self.tampilTambahButton.setCheckable(True)
        #self.tampilTambahButton.setAutoDefault(False)
        #self.outerGridLayout.addWidget(self.tampilTambahButton, 7, 0, 1, 1)
        
        self.toolTambahButton = QtGui.QToolButton(self.gridLayoutWidget)
        #self.toolTambahButton.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/go_top"), QtGui.QIcon.Normal, QtGui.QIcon.On)
        icon.addPixmap(QtGui.QPixmap(":/go_bottom"), QtGui.QIcon.Selected, QtGui.QIcon.On)
        self.toolTambahButton.setIcon(icon)
        self.toolTambahButton.setIconSize(QtCore.QSize(16, 20))
        self.toolTambahButton.setCheckable(True)
        self.toolTambahButton.setChecked(False)
        self.toolTambahButton.setArrowType(QtCore.Qt.NoArrow)
        self.toolTambahButton.setObjectName("toolTambahButton")
        self.outerGridLayout.addWidget(self.toolTambahButton, 7, 0, 1, 1)
        
        self.utamaButtonBox = QtGui.QDialogButtonBox(self.gridLayoutWidget)
        self.utamaButtonBox.setOrientation(QtCore.Qt.Horizontal)
        self.utamaButtonBox.setStandardButtons(QtGui.QDialogButtonBox.Discard|QtGui.QDialogButtonBox.SaveAll)
        self.utamaButtonBox.setObjectName("utamaButtonBox")
        self.outerGridLayout.addWidget(self.utamaButtonBox, 7, 1, 1, 4)
        
        self.retranslateUi(Dialog)
        self.toolBox.setCurrentIndex(0)
        self.toolBox.hide()
        self.supplierComboBox.activated.connect(self.showSupplier)
        self.pembayaranComboBox.activated.connect(self.showPembayaran)
        self.hargaBeliGrosirEdit.textEdited[str].connect(self.formatDecimal)
        #self.toolboxButtonBox.button(QtGui.QDialogButtonBox.Reset).clicked.connect(clearItemFields)
        self.toolboxButtonBox.button(QtGui.QDialogButtonBox.Save).clicked.connect(self.addNotaItem)
        self.buatNotaButton.toggled.connect(self.createNota)
        #self.tampilTambahButton.toggled.connect(self.toolBox.setVisible)
        self.toolTambahButton.toggled.connect(self.toolBox.setVisible)
        self.utamaButtonBox.button(QtGui.QDialogButtonBox.SaveAll).clicked.connect(self.saveNota)
        #QtCore.QObject.connect(self.utamaButtonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
        #QtCore.QObject.connect(self.utamaButtonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
        #QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
        self.idLabel.setText(QtGui.QApplication.translate("Dialog", "ID :", None, QtGui.QApplication.UnicodeUTF8))
        self.supplierLabel.setText(QtGui.QApplication.translate("Dialog", "&Supplier", None, QtGui.QApplication.UnicodeUTF8))
        self.hargaBeliTotalLabel.setText(QtGui.QApplication.translate("Dialog", "&Total", None, QtGui.QApplication.UnicodeUTF8))
        self.tanggalLabel.setText(QtGui.QApplication.translate("Dialog", "Tangga&l", None, QtGui.QApplication.UnicodeUTF8))
        self.pembayaranLabel.setText(QtGui.QApplication.translate("Dialog", "Pem&bayaran", None, QtGui.QApplication.UnicodeUTF8))
        self.tanggalEdit.setDisplayFormat(QtGui.QApplication.translate("Dialog", "d - MMMM - yyyy", None, QtGui.QApplication.UnicodeUTF8))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page), QtGui.QApplication.translate("Dialog", "Tambah &Item", None, QtGui.QApplication.UnicodeUTF8))
        self.buatNotaButton.setText(QtGui.QApplication.translate("Dialog", "Buat &Nota", None, QtGui.QApplication.UnicodeUTF8))
        self.qtyLabel.setText(QtGui.QApplication.translate("Dialog", "&Qty", None, QtGui.QApplication.UnicodeUTF8))
        self.unitLabel.setText(QtGui.QApplication.translate("Dialog", "&Unit", None, QtGui.QApplication.UnicodeUTF8))
        self.produkLabel.setText(QtGui.QApplication.translate("Dialog", "&Produk", None, QtGui.QApplication.UnicodeUTF8))
        self.hargaBeliGrosirLabel.setText(QtGui.QApplication.translate("Dialog", "&Harga Grosir", None, QtGui.QApplication.UnicodeUTF8))
        self.toolboxButtonBox.button(QtGui.QDialogButtonBox.Reset).setText(QtGui.QApplication.translate("Dialog", "&Reset", None, QtGui.QApplication.UnicodeUTF8))
        self.toolboxButtonBox.button(QtGui.QDialogButtonBox.Save).setText(QtGui.QApplication.translate("Dialog", "Sa&ve", None, QtGui.QApplication.UnicodeUTF8))
        #self.tampilTambahButton.setText(QtGui.QApplication.translate("Dialog", "Ta&mbah", None, QtGui.QApplication.UnicodeUTF8))
        self.toolTambahButton.setShortcut(QtGui.QApplication.translate("Dialog", "+", None, QtGui.QApplication.UnicodeUTF8))
        self.utamaButtonBox.button(QtGui.QDialogButtonBox.Discard).setText(QtGui.QApplication.translate("Dialog", "&Discard", None, QtGui.QApplication.UnicodeUTF8))
        self.utamaButtonBox.button(QtGui.QDialogButtonBox.SaveAll).setText(QtGui.QApplication.translate("Dialog", "Save &All", None, QtGui.QApplication.UnicodeUTF8))
        
    def setupNota(self):
        # database
        self.db = connection.database()        
        self.db.initDB()
        self.db.initTables()
        self.db.initTablesFields()
        self.transactionStarted = self.db.startTransactions()

        # supplier completer
        self.supplierCompleter = QtGui.QCompleter(self.gridLayoutWidget)
        self.supplierCompleter.setMaxVisibleItems(10)

        self.supplierModel = QtSql.QSqlTableModel(self.supplierCompleter)
        self.supplierQuery = QtSql.QSqlQuery("SELECT id, supplier_nama FROM db_supplier")
        self.supplierModel.setQuery(self.supplierQuery)

        self.supplierCompleter.setModel(self.supplierModel)
        self.supplierCompleter.setCompletionColumn(1)

        # jenis pembayaran
        self.model_pembayaran = QtGui.QStringListModel(['KONTAN','BON'])

        # unit
        self.model_unit = QtGui.QStringListModel(['kg','m','ltr','lbr','dus','lsn','buah','bks','pcs'])

        # item completer
        self.produkCompleter = QtGui.QCompleter(self.gridLayoutWidget)
        self.produkCompleter.setMaxVisibleItems(13)

        self.produkModel = QtSql.QSqlTableModel(self.produkCompleter)
        self.produkQuery = QtSql.QSqlQuery("SELECT id, nama FROM db_produk")
        self.produkModel.setQuery(self.produkQuery)

        self.produkCompleter.setModel(self.produkModel)
        self.produkCompleter.setCompletionColumn(1)

        # nota atribut
        self.last_nota_id = None
        self.last_item_id = None
        self.produk_ids = []
        self.last_harga_beli_total = None


    def createNota(self):
        self.createNotaQuery = QtSql.QSqlQuery()
        self.createNotaQuery.prepare("INSERT INTO db_nota(tanggal, db_supplier_id, pembayaran, harga_beli_total) \
                                VALUES(:tanggal, :db_supplier_id, :pembayaran, :harga_beli_total)")
        self.createNotaQuery.bindValue(":tanggal", self.tanggalEdit.date())
        self.createNotaQuery.bindValue(":db_supplier_id", self.supplierComboBox.itemData(self.supplierComboBox.currentIndex()))
        self.createNotaQuery.bindValue(":pembayaran", self.pembayaranComboBox.currentText())
        self.createNotaQuery.bindValue(":harga_beli_total", self.hargaBeliTotalEdit.text())

        if self.createNotaQuery.exec_():
           self.last_nota_id = self.createNotaQuery.lastInsertId()
           print 'Create Nota OK'
           print 'Bound Value: ', self.createNotaQuery.boundValues()
           print 'Last nota ID: ', self.last_nota_id
           self.idEdit.setText(unicode(self.last_nota_id))
           self.buatNotaButton.setDisabled(True)
        else:
           print 'Create Nota Failed'
           print 'Bound Value: ', self.createNotaQuery.boundValues()


    def addNotaItem(self):
        # TODO: 
        #      1. Pop warning for empty field
        #      2. Stretch cell properly
        print 'Produk IDs: ', self.produk_ids
        print 'Combo Current Index: ', self.produkComboBox.itemData(self.produkComboBox.currentIndex())
        if self.last_nota_id is not None and self.produk_ids.__contains__(self.produkComboBox.itemData(self.produkComboBox.currentIndex())) is False:
            self.addNotaItemQuery = QtSql.QSqlQuery()
            self.addNotaItemQuery.prepare("INSERT INTO db_nota_produk__db_produk_nota(db_nota_id, db_produk_id, jumlah_beli, su, harga_beli_satuan, harga_beli_grosir) \
                                    VALUES(:db_nota_id, :db_produk_id, :jumlah_beli, :su, :harga_beli_satuan, :harga_beli_grosir)")
            qtyItem = self.qtyEdit.text()
            hargaBeliGrosir = self.hargaBeliGrosirEdit.text().replace(format.groupSeparator, '')
            hargaBeliSatuan = Decimal(hargaBeliGrosir)/Decimal(qtyItem)
            hargaBeliSatuan = hargaBeliSatuan.quantize(Decimal('.01'), rounding=ROUND_DOWN, watchexp=0)

            self.addNotaItemQuery.bindValue(":db_nota_id", self.last_nota_id)
            self.addNotaItemQuery.bindValue(":db_produk_id", self.produkComboBox.itemData(self.produkComboBox.currentIndex()))
            self.addNotaItemQuery.bindValue(":jumlah_beli", qtyItem)
            self.addNotaItemQuery.bindValue(":su", self.unitComboBox.currentText())
            self.addNotaItemQuery.bindValue(":harga_beli_satuan", str(hargaBeliSatuan))
            self.addNotaItemQuery.bindValue(":harga_beli_grosir", hargaBeliGrosir)
    
            if self.addNotaItemQuery.exec_():
               self.last_item_id = self.addNotaItemQuery.lastInsertId()
               self.produk_ids.append(self.produkComboBox.itemData(self.produkComboBox.currentIndex()))
               print 'Add item OK'
               print 'Bound Value: ', self.addNotaItemQuery.boundValues()
               print 'Last item ID: ', self.last_item_id
               
               if self.tableView.model() == None:
                  self.viewName = 'view_nota_items'
                  self.viewHeaderLabel = dict(jumlah_beli='Qty', su='Unit', nama='Barang', harga_beli_satuan='Harga Satuan', harga_beli_grosir='Harga Total')
    
                  self.viewModel = model.tableModel(self.db)
                  
                  self.viewModel.setTable(tableName = self.viewName)
                  self.viewModel.setFilter("db_nota_id='%s'" % self.last_nota_id)
                  self.viewModel.loadModel()
                  # FIX:
                  # Use lib.view.viewTable instead of QTableView that provides column hiding
                  self.tableView.setModel(self.viewModel.model)
               else:
                  self.viewModel.reloadModel()
    
               self.resetNotaItemFields()
    
               # refine this
               self.recalculateHargaBeliTotalQuery = QtSql.QSqlQuery("SELECT SUM(harga_beli_grosir) FROM db_nota_produk__db_produk_nota WHERE `db_nota_id` = %s" % self.last_nota_id)
               self.recalculateHargaBeliTotalQuery.next()
               self.last_harga_beli_total = self.recalculateHargaBeliTotalQuery.value(0)
               self.hargaBeliTotalEdit.setText(format.formatDecimal(self.last_harga_beli_total))
    
            else:
               print 'Add item Failed'
               print 'Bound Value: ', self.addNotaItemQuery.boundValues()
               print 'Last Query: ', self.addNotaItemQuery.lastQuery()
               print 'Last Error: ', self.addNotaItemQuery.lastError()

    
    def saveNota(self):
        # Pastikan bahwa entry item terakhir valid
        if self.last_item_id is not None:
            self.updateNotaQuery = QtSql.QSqlQuery()
            self.updateNotaQuery.prepare("UPDATE db_nota SET `harga_beli_total`= :harga_beli_total WHERE `id`= :db_nota_id")
            self.updateNotaQuery.bindValue(":harga_beli_total", self.last_harga_beli_total)
            self.updateNotaQuery.bindValue(":db_nota_id", self.last_nota_id)
    
            if self.updateNotaQuery.exec_():
                self.db.commitTransactions()
                print 'Save Nota OK'
                print 'Last Query: ', self.updateNotaQuery.lastQuery()
            else:
                self.db.rollbackTransactions()
                print 'Save Nota Failed'
                print 'Last Query: ', self.updateNotaQuery.lastQuery()
                print 'Last Error: ', self.updateNotaQuery.lastError()


    def resetNotaItemFields(self):
        # reset add item fields to blank
        self.qtyEdit.clear()
        self.unitComboBox.clearEditText()
        self.produkComboBox.clearEditText()
        self.hargaBeliGrosirEdit.clear()

    
    def setupLocale(self):
        self.locale = config.application['locale']

    
    def formatDecimal(self, number):
        self.hargaBeliGrosirEdit.setText(format.formatDecimal(number))

    
    def showToolBox(self):
        self.toolBox.show()

    
    def showSupplier(self, comboText = ''):
        print 'ComboBox Index: ', comboText
        print 'ComboBox Data: ', self.supplierComboBox.itemData(self.supplierComboBox.currentIndex())

    
    def showPembayaran(self, comboText = ''):
        print self.pembayaranComboBox.itemText(comboText)


    #def 


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

"""
TODO:
4. Make nota item input separate window
5. Provide button to add brand new item(non-listed item from db_produk)
6. When adding brand new item, show possible similar item to prevent multiple input.

7. since nota is per-store proof of purchase and wont be merge with other store's notas
   so it is enough to say that db_nota insert is parallel with one item or more entries, no item
   entry means canceled nota.
8. In order to make note of potential broken nota we make TODAY NOTIFICATION on the app, hence
   people would notice if there's a broken nota or not.
 select n.id, n.tanggal, s.supplier_nama, n.pembayaran, n.harga_beli_total from db_nota as n left join db_supplier as s on n.db_supplier_id=s.id order by tanggal desc limit 1;

"""
